package com.sushi.service.impl;

import com.sushi.enums.Type;
import com.sushi.repository.entity.TagEntity;
import com.sushi.repository.entity.TagRelationEntity;
import com.sushi.repository.mapper.TagMapper;
import com.sushi.request.TagRelationReq;
import com.sushi.response.PostResp;
import com.sushi.service.TagRelationService;
import com.sushi.service.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sushi.response.ResponseBO;
import com.sushi.response.ResponsePageBO;
import com.sushi.response.TagResp;
import com.sushi.request.TagReq;
import com.sushi.request.TagPageReq;
import com.sushi.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sushi.exception.BusinessException;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 标签 服务实现类
 * @date 2023-05-02
 * @time 17:15:59
 * @author Administrator
 */
@Slf4j
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, TagEntity> implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private TagRelationService relationService;

    

    /**
     * 新增
     */
    @Override
    public ResponseBO<TagResp> add(TagReq req) {
        TagEntity entity = BeanUtil.convert(req, TagEntity.class);
        if (ObjectUtil.isEmpty(entity)) {
            throw new BusinessException("保存失败");
        }
        entity.insert();
        return ResponseUtil.ok(BeanUtil.convert(entity, TagResp.class));
    }

    /**
     * 逻辑删除
     */
    @Override
    public ResponseBO<TagResp> logicRemove(TagReq req) {
        if (StringUtil.isBlank(req.getId())) {
            throw new BusinessException("id不能为空");
        }
        TagEntity entity = new TagEntity();
        entity.setId(req.getId());
        entity.setDeleted(1L);
        entity.updateById();
        return ResponseUtil.ok(BeanUtil.convert(entity, TagResp.class));
    }

    /**
     * 更新
     */
    @Override
    public ResponseBO<TagResp> updateByField(TagReq req) {
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getId())) {
            throw new BusinessException("必要参数不能为空");
        }
        TagEntity entity = getById(req.getId());
        if (ObjectUtil.isEmpty(entity)) {
            return ResponseUtil.error("信息不存在，无法更新");
        }
        if (StringUtil.isNotBlank(req.getName())) {
            entity.setName(req.getName());
        }
        if (StringUtil.isNotBlank(req.getType())) {
            entity.setType(req.getType());
        }
        if (ObjectUtil.isNotEmpty(req.getHotCount())) {
            entity.setHotCount(req.getHotCount());
        }
        entity.setGmtModifyTime(LocalDateTime.now());
        entity.updateById();
        log.info("更新成功：{}", JSON.toJSONString(entity));
        return ResponseUtil.ok(BeanUtil.convert(entity, TagResp.class));
    }

    /**
     * 列表
     */
    @Override
    public ResponsePageBO<TagResp> listByCondition(TagPageReq req) {
        if (ObjectUtil.isEmpty(req) || ObjectUtil.isEmpty(req.getPageNum()) || ObjectUtil.isEmpty(req.getPageSize())) {
            throw new BusinessException("必要参数不能为空");
        }
        LambdaQueryWrapper<TagEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TagEntity::getDeleted, 0L);
//        wrapper.eq(StringUtil.isNotBlank(req.getId()), TagEntity::getId, req.getId());
        wrapper.like(StringUtil.isNotBlank(req.getName()), TagEntity::getName, req.getName());
        wrapper.eq(StringUtil.isNotBlank(req.getType()), TagEntity::getType, req.getType());

        wrapper.orderByDesc(TagEntity::getGmtCreateTime);

        Page<TagEntity> page = page(new Page<>(req.getPageNum(), req.getPageSize()), wrapper);
        if (ObjectUtil.isEmpty(page) || CollectionUtil.isEmpty(page.getRecords())) {
            return ResponsePageUtil.ok(req, new ArrayList<>(), 0L);
        }
        List<TagResp> convert = BeanUtil.convert(page.getRecords(), TagResp.class);
        return ResponsePageUtil.ok(req, convert, page.getTotal());
    }

    /**
     * 详情
     */
    @Override
    public ResponseBO<TagResp> detail(TagReq req) {
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getId())) {
            throw new BusinessException("必要参数不能为空");
        }
        TagEntity entity = getById(req.getId());
        if (ObjectUtil.isEmpty(entity)) {
            throw new BusinessException("对象不存在");
        }
        return ResponseUtil.ok(BeanUtil.convert(entity, TagResp.class));
    }

    @Override
    public ResponseBO<List<TagResp>> listByType(TagReq req) {
        if (StringUtil.isBlank(req.getType())) {
            throw new BusinessException("类型不能为空");
        }
        List<TagEntity> list = list(new LambdaQueryWrapper<TagEntity>().eq(TagEntity::getDeleted, 0L).eq(TagEntity::getType, req.getType())
                .orderByDesc(TagEntity::getHotCount).orderByDesc(TagEntity::getGmtCreateTime));
        return CollectionUtil.isEmpty(list) ? ResponseUtil.ok(new ArrayList<>()) : ResponseUtil.ok(BeanUtil.convert(list, TagResp.class));
    }

    @Override
    public List<String> getRalationIdList(List<String> tagIdList, Type.Tag type) {
        if (CollectionUtil.isEmpty(tagIdList)) {
            return new ArrayList<>();
        }
        List<TagRelationEntity> list = relationService.list(new LambdaQueryWrapper<TagRelationEntity>().eq(TagRelationEntity::getDeleted, 0L)
                .eq(TagRelationEntity::getTagType, type.getCode()).in(TagRelationEntity::getTagId, tagIdList));
        List<String> idList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(re -> idList.add(re.getObjId()));
        }
        return idList;
    }

    @Override
    public void saveRelation(List<String> tagIdList, String objId, Type.Tag objType) {
        if (CollectionUtil.isEmpty(tagIdList) || StringUtil.isBlank(objId)) {
            return;
        }
        tagIdList.forEach(tagId -> {
            TagRelationReq relationReq = new TagRelationReq();
            relationReq.setTagId(tagId);
            relationReq.setTagType(objType.getCode());
            relationReq.setObjId(objId);
            relationReq.setObjType(objType.getCode());
            relationService.add(relationReq);
            // 统计热度，每使用一次就+1
            TagEntity tag = getById(tagId);
            if (tag != null) {
                tag.setHotCount(tag.getHotCount() + 1);
                tag.updateById();
            }
        });

    }

    @Override
    public List<TagResp> getTagListByObjId(String objId, Type.Tag type) {
        List<String> tagIdList = relationService.getTagIdListByObj(objId, type);
        if (CollectionUtil.isNotEmpty(tagIdList)) {
            List<TagEntity> entityList = list(new LambdaQueryWrapper<TagEntity>().eq(TagEntity::getDeleted, 0L).in(TagEntity::getId, tagIdList));
            if (CollectionUtil.isNotEmpty(entityList)) {
                return BeanUtil.convert(entityList, TagResp.class);
            }
        }
        return new ArrayList<>();
    }


}